#include <stdio.h>

#include "thread.h"
#include "ipc.h"

//#define USING_STATIC
#define TH3_MASK 0X01
#define TH2_MASK 0X06


#ifdef USING_STATIC
static mt_event_t event;
#endif

static mt_event_t *pevent;


static void *thread1_func(void *arg)
{
    mt_uint32_t recved;
    mt_err_t err;
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        err = mt_event_recv(pevent, 
                            TH3_MASK|TH2_MASK, 
                            MT_EVENT_FLAG_OR|MT_EVENT_FLAG_CLEAR,
                            MT_WAITING_FOREVER,
                            &recved);
        if(err == MT_EOK)
        {
            if((recved & TH2_MASK) == TH2_MASK)
                printf("frome thread2\r\n");
            if((recved & TH3_MASK) == TH3_MASK)
                printf("frome thread3\r\n");
        }
        else
            printf("take event failed\r\n");
    }
}

static void *thread2_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        mt_event_send(pevent, TH2_MASK);
        mt_delay(1000);
    }
}

static void *thread3_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        mt_event_send(pevent, TH3_MASK);
        mt_delay(2000);
    }
}

int event_test(void)
{
    mt_thread_t *thread1_handle;
    mt_thread_t *thread2_handle;
    mt_thread_t *thread3_handle;

#ifdef USING_STATIC
    mt_event_init(&event, "test_event", MT_IPC_FLAG_FIFO);
    pevent = &event;
#else
    pevent = mt_event_create("test_event", MT_IPC_FLAG_FIFO);
    if(pevent == MT_NULL)
    {
        printf("create event faied\r\n");
        return -1;
    }
#endif
    
    thread1_handle = mt_thread_create("thread1", 
                                      thread1_func, 
                                      "thread1", 
                                      1024, 
                                      12, 
                                      5);
    thread2_handle = mt_thread_create("thread2", 
                                      thread2_func, 
                                      "thread2", 
                                      1024, 
                                      11, 
                                      5);
    thread3_handle = mt_thread_create("thread3", 
                                      thread3_func, 
                                      "thread3", 
                                      1024, 
                                      10, 
                                      5);
    if((thread1_handle == MT_NULL) || (thread2_handle == MT_NULL) || (thread3_handle == MT_NULL))
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(thread1_handle);
    mt_thread_start(thread2_handle);
    mt_thread_start(thread3_handle);
    
    return 0;
}
